// -*- coding: utf-8 -*- 
/**
 * Project: Java8InActionT
 * Creator: yanking
 * Create time: 2022-02-19 15:39
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.StreamTrain.forkAndJoin;

import java.util.concurrent.RecursiveTask;

public class forkAndJoin extends RecursiveTask<Long> {
    private final long[] numbers; // the array to sum
    private final int start;
    private final int end;
    private final long THRESHOLD = 10_000;

    public forkAndJoin(long[] numbers) {
        this(numbers, 0, numbers.length);
    }

    public forkAndJoin(long[] numbers, int start, int end) {
        this.numbers = numbers;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        int length = end - start;
        if (length <= THRESHOLD) {
            return computeSequentially();
        }
        forkAndJoin leftTask = new forkAndJoin(numbers, start, start + length / 2);
        leftTask.fork();
        forkAndJoin rightTask = new forkAndJoin(numbers, start + length / 2, end);
        long rightRes = rightTask.compute();
        long leftRes = leftTask.join();
        return leftRes + rightRes;
    }
    private long computeSequentially() {
        long res = 0L;
        for (long number : numbers) {
            res += number;
        }
        return res;
    }
}
